package dao_sys

import (
	"wrblog-api-go/app/model"
	"wrblog-api-go/app/model/model_sys"
	"wrblog-api-go/pkg/errs"
	"wrblog-api-go/pkg/mysql"
	"wrblog-api-go/pkg/utils"
)

func GetPageList(sysConfig model_sys.SelectSysConfig) (sysConfigs []model_sys.SysConfigVo, total int64, err error) {
	db := mysql.Db().Model(&model_sys.SysConfigPo{})
	if sysConfig.ConfigName != "" {
		db = db.Where("config_name like ?", "%"+sysConfig.ConfigName+"%")
	}
	if sysConfig.ConfigKey != "" {
		db = db.Where("config_key like ?", "%"+sysConfig.ConfigKey+"%")
	}
	if !sysConfig.StartTime.IsZero() {
		db = db.Where("create_time >= ?", sysConfig.StartTime)
	}
	if !sysConfig.EndTime.IsZero() {
		db = db.Where("create_time <= ?", sysConfig.EndTime)
	}
	db = db.Where("deleted = '0'").Count(&total).Order("create_time desc")
	if sysConfig.PageNum != nil && sysConfig.PageSize != nil {
		db = db.Limit(*sysConfig.PageSize).Offset((*sysConfig.PageNum - 1) * *sysConfig.PageSize)
	} else {
		db = db.Limit(10)
	}
	err = errs.ErrNotFound(db.Find(&sysConfigs).Error)
	return
}

func GetSysConfigById(configId int) (sysConfig model_sys.SysConfigVo, err error) {
	db := mysql.Db().Model(&model_sys.SysConfigPo{})
	err = db.Where("config_id = ? and deleted = '0'", configId).First(&sysConfig).Error
	err = errs.ErrNotFound(err)
	return
}

func AddSysConfig(sysConfig model_sys.SysConfigPo) (int, error) {
	err := mysql.Db().Create(&sysConfig).Error
	return sysConfig.ConfigId, errs.ErrNotFound(err)
}

func EditSysConfig(sysConfig model_sys.SysConfigPo) (int64, error) {
	res := mysql.Db().Updates(&sysConfig)
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func RemoveSysConfig(configIds []string, uk string) (int64, error) {
	db := mysql.Db().Model(&model_sys.SysConfigPo{})
	db.Where("config_id in (?)", configIds)
	res := db.Updates(&model_sys.SysConfigPo{BaseEntity: model.BaseEntity{UpdateTime: utils.NewTimeNow(), UpdateBy: uk, Deleted: "1"}})
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func DeleteSysConfig(configIds []string) (int64, error) {
	db := mysql.Db().Model(&model_sys.SysConfigPo{})
	res := db.Delete(&model_sys.SysConfigPo{}, configIds)
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func GetInfoByKey(key string) (sysConfig *model_sys.SysConfigPo, err error) {
	err = mysql.Db().Where("config_key = ? and deleted = '0'", key).First(&sysConfig).Error
	err = errs.ErrNotFound(err)
	return
}
